package DCSource.Archive;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.zip.ZipFile;
import DCSource.ConfigManager.*;

public class DataPack {
	String file;
	ArrayList<toZipFile> list = new ArrayList<toZipFile>();
	Table main = new Table("DefaultMain.conf");
	public DataPack(String file){
		this.file = file;
		if (exist()){
			Zipfile Zip = new Zipfile(this.file);
			list = Zip.dePack();
			if (!getMain().equals("ERROR")){
				if (Zip.exist(getMain())){
					main.setName(getMain());
					main.SetSource(Zip.ReadText(getMain()));
				}
				for (int I=0;I<list.size();I++){
					if (list.get(I).getName().equals(getMain())){
						list.remove(I);
						break;
					}
				}
			}
		}
	}
	public boolean exist(){
		File src = new File(file);
		return src.exists();
	}
	public String getMain(){
		if (exist()){
			try {
				ZipFile file = new ZipFile(this.file);
				if (file.getComment().startsWith("DCSOURCE")){
					return file.getComment().substring(("DCSOURCE").length(), file.getComment().length());
				}else{
					return "ERROR";
				}
			} catch (IOException e) {
				return "ERROR";
			}
		}else{
			return "ERROR";
		}
	}
	public String getMain(String otherFile){
		if (exist()){
			try {
				ZipFile file = new ZipFile(otherFile);
				if (file.getComment().startsWith("DCSOURCE")){
					return file.getComment().substring(("DCSOURCE").length(), file.getComment().length());
				}else{
					return "ERROR";
				}
			} catch (IOException e) {
				return "ERROR";
			}
		}else{
			return "ERROR";
		}
	}
	public void importFile(String ifile){
		if (exist()){
			try {
				Zipfile importing = new Zipfile(ifile);
				ArrayList<toZipFile> list = importing.dePack();
				for (int I=0;I<list.size();I++){
					if (list.get(I).getName().equalsIgnoreCase(getMain())==false){
						this.list.add(list.get(I));
					}
				}
			}catch(Exception err){
				
			}
		}
	}
	public void renameConfig(String file){
		this.main.setName(file);
	}
	public Table getConfig(){
		return this.main;
	}
	public byte[] getFile(String file){
		byte[] re = new byte[]{};
		for (int I=0;I<this.list.size();I++){
			if (this.list.get(I).getName().equals(file)){
				re = this.list.get(I).getSRC();
				break;
			}
		}
		return re;
	}
	public void save(){
		Zipfile saver = new Zipfile(this.file);
		list.add(new toZipFile(this.main.getName().getName(),this.main.getSource().getBytes()));
		saver.packFiles(this.list, 9, "DCSOURCE"+this.main.getName());
		list.remove(new toZipFile(this.main.getName().getName(),this.main.getSource().getBytes()));
	}
}
